<?php namespace Common\Model;
use Hdphp\Model\Model;
class Goods extends Model{
	//固定写法  指定表名
	protected $table="goods";
	protected $validate=array(
		array('gname','required','商品名称不能为空',3,3)
	);
	//自定义添加
	public function store(){
	    //触发自动验证
	    if(!$this->create()) return false;
		//把图片地址压入数据库
		//检测$_POST['pic']是否存在
		if(isset($_POST['pic'])){
			$path=$_POST['pic'];
			$this->data['pic']=$path;
		}
//		p($data);exit;
		//把时间压入数据库
		$this->data['time']=time();
//		p($_POST);
		//2.给商品详情表添加数据
		$gid = $this->add();
		$detailModel=new \Common\Model\Detail;
//		p($_POST);die;
		$detailModel->create();
		$detailModel->data['goods_gid']=$gid;
		//把数组变为字符串，把多张图片压入到数据库
		$detailModel->data['dpic']=implode('|', Q('post.dpic',array()));
		$detailModel->add();

		//3.给商品属性表里添加数据
		$attrModel=new \Common\Model\Goodsattr;
//		p($_POST);exit;
		//规格添加
		foreach (Q('post.spec',array()) as $k => $v){
			foreach ($v['value'] as $kk => $vv) {
				if(!empty($vv)){
					$add = array(
						'gtvalue' => $vv,
						'added'   => $v['price'][$kk],
						'typeattr_taid' => $k,
						'goods_gid' => $gid
					);
					$attrModel->add($add);	
				}			
			}
		}
		//属性添加
		foreach (Q('post.attr',array()) as $k=>$v){
			if(!empty($v)){
				$data=array(
					'gtvalue'=>$v,
					'typeattr_taid' => $k,
					'goods_gid' => $gid
				);
				$attrModel->add($data);	
			}		
		}
		return true;
	}
	//编辑模型
	public function edit(){
		$gid=Q('post.gid',0,'intval');
		if(!$this->create()) return false;
		//1修改商品表
//		p($_POST);die;
		$this->data['pic']=Q('post.pic');
		$this->save();
		//2修改商品详细表
		$detailModel=new \Common\Model\Detail;
//		$detailModel->data['goods_gid']=$gid;
		//把数组变为字符串，把多张图片压入到数据库
		$detailModel->data['dpic']=implode('|', Q('post.dpic',array()));
		$detailModel->data['intro']=Q('post.intro');
		$detailModel->data['service']=Q('post.service');
		$detailModel->where("goods_gid=$gid")->save();
//		p($detailModel);die;
		//3修改表article_tag
		//先删除
		$attrModel=new \Common\Model\Goodsattr;
		$attrModel->where("goods_gid=$gid")->delete();
		//再添加
//		p($_POST);
		//规格添加
		foreach (Q('post.spec',array()) as $k => $v){
			if(isset($v['value'])){
				foreach ($v['value'] as $kk => $vv) {
					if(!empty($vv)){
						$add = array(
							'gtvalue' => $vv,
							'added'   => $v['price'][$kk],
							'typeattr_taid' => $k,
							'goods_gid' => $gid
						);
						$attrModel->add($add);	
					}			
				}
			}
			
		}
		//属性添加
		foreach (Q('post.attr',array()) as $k=>$v){
			if(!empty($v)){
				$data=array(
					'gtvalue'=>$v,
					'typeattr_taid' => $k,
					'goods_gid' => $gid
				);
				$attrModel->add($data);	
			}		
		}
		return true;
	}

}

 ?>